package com.qg.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qg.dto.ReturnResult;
import com.qg.pojo.QgGoods;
import com.qg.pojo.QgGoodsTempStock;
import com.qg.pojo.QgOrder;
import com.qg.service.LocalGoodsService;
import com.qg.service.QgGoodsService;
import com.qg.service.QgGoodsTempStockService;
import com.qg.service.QgOrderService;
import com.qg.utils.*;
import com.qg.vo.QgGoodsMessageVo;
import com.qg.vo.QgGoodsVo;
import com.qg.vo.QgUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class LocalGoodsServiceImpl implements LocalGoodsService {
    @Reference
    private QgGoodsService qgGoodsService;
    @Reference
    private QgGoodsTempStockService qgGoodsTempStockService;
    @Reference
    private QgOrderService qgOrderService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ActiveMqUtil activeMqUtil;

    @Override
    public QgGoodsVo getQgGoodsById(String id) throws Exception {
        String qgGoodsjson=redisUtil.getStr(id);
        QgGoodsVo qgGoodsVo=new QgGoodsVo();
        if(EmptyUtils.isEmpty(qgGoodsjson)){
            QgGoods qgGoods=qgGoodsService.getQgGoodsById(id);
            Map<String,Object> param=new HashMap<>();
            param.put("goodsId",id);
            param.put("status",0);
            Integer count=qgGoodsTempStockService.getQgGoodsTempStockCountByMap(param);
            BeanUtils.copyProperties(qgGoods,qgGoodsVo);
            qgGoodsVo.setTempStock(qgGoods.getStock()-count);
            String qgGoodsJson=JSON.toJSONString(qgGoodsVo);
            redisUtil.setStr(Constants.goods+"id",qgGoodsJson);
        }else {
            qgGoodsVo= JSONObject.parseObject(qgGoodsjson,QgGoodsVo.class);
        }
        return qgGoodsVo;
    }

    @JmsListener(destination = "qg:goods")
    private void getGoods(QgGoodsMessageVo qgGoodsMessageVo) throws Exception {
            String goodsId=qgGoodsMessageVo.getGoodsId();
            String userId=qgGoodsMessageVo.getGoodsId();

            while (!redisUtil.lock(Constants.Lock.lockPrefix+goodsId,Constants.Lock.time)){
                Thread.sleep(3);
            }
            //2.判断用户是否已经抢购过商品
            Map<String,Object>param=new HashMap<String,Object>( );
            param.put("goodsId",goodsId);
            param.put("status",1);
            param.put("userId",userId);
            List<QgGoodsTempStock> qgGoodsTempStockList=qgGoodsTempStockService.getQgGoodsTempStockListByMap(param);
            if (EmptyUtils.isNotEmpty(qgGoodsTempStockList)){
                redisUtil.unlock(Constants.Lock.lockPrefix+goodsId);
                return;
            }
            String goodsJSON=redisUtil.getStr(Constants.goods+goodsId);
            QgGoodsVo qgGoodsVo=JSONObject.parseObject(goodsJSON,QgGoodsVo.class);
            //判断库存是否充足
            if (qgGoodsVo.getTempStock()<=0){
                redisUtil.unlock(Constants.Lock.lockPrefix+goodsId);
                return;
            }
            //更新库存表数据
            QgGoodsTempStock qgGoodsTempStock1=new QgGoodsTempStock();
            qgGoodsTempStock1.setId(IdWorker.getId());
            qgGoodsTempStock1.setGoodsId(goodsId);
            qgGoodsTempStock1.setUserId(userId);
            qgGoodsTempStock1.setStatus(1);
            qgGoodsTempStock1.setCreatedTime(new Date());
            qgGoodsTempStock1.setUpdatedTime(null);
            qgGoodsTempStockService.qdtxAddQgGoodsTempStock(qgGoodsTempStock1);
            qgGoodsVo.setTempStock(qgGoodsVo.getTempStock()-1);
            String newJSON=JSONObject.toJSONString(qgGoodsVo);
            //生产订单
            addOrder(qgGoodsTempStock1,qgGoodsVo.getPrice());
            redisUtil.setStr(Constants.goods+qgGoodsVo.getId(),newJSON);
            redisUtil.unlock(Constants.Lock.lockPrefix+goodsId);
    }

    private void addOrder(QgGoodsTempStock qgGoodsTempStock,Double amount)throws Exception{
        QgOrder qgOrder=new QgOrder();
        qgOrder.setId(IdWorker.getId());
        qgOrder.setUserId(qgGoodsTempStock.getUserId());
        qgOrder.setGoodsId(qgGoodsTempStock.getGoodsId());
        qgOrder.setStockId(qgGoodsTempStock.getId());
        qgOrder.setNum(1);
        qgOrder.setAmount(amount);
        qgOrder.setStatus(qgGoodsTempStock.getStatus());
        qgOrder.setCreatedTime(new Date());
        qgOrder.setOrderNo("Qg001"+new Date()+MD5.getMd5(qgOrder.getId(),12));
        qgOrderService.qdtxAddQgOrder(qgOrder);
    }

    @Override
    public ReturnResult sendGoodsMessage(String token, String goodsId)throws Exception{
        String userJson=redisUtil.getStr(token);
        QgUserVo qgUserVo=JSONObject.parseObject(userJson, QgUserVo.class);
        String userId=null;
        if (EmptyUtils.isNotEmpty(qgUserVo)){
            userId=qgUserVo.getId();
            QgGoodsMessageVo qgGoodsMessageVo=new QgGoodsMessageVo();
            qgGoodsMessageVo.setUserId(userId);
            qgGoodsMessageVo.setGoodsId(goodsId);
            activeMqUtil.sendQueueMessage("qg:goods",qgGoodsMessageVo);
            return ReturnResultUtil.resultSuccess();
        }
        return ReturnResultUtil.returnFile(2005,"出错");
    }
}
